<?php

namespace app\queue\redis\order;

use app\services\RequestService;
use plugin\admin\app\model\IgnoreGood;
use plugin\admin\app\model\NetworkOrder;
use plugin\admin\app\model\Order;
use plugin\admin\app\model\PriceLog;
use plugin\admin\app\model\RechargeLog;
use plugin\admin\app\model\RequestLog;
use plugin\admin\app\model\YbUser;
use support\Cache;
use support\Db;
use support\Log;
use Webman\RedisQueue\Consumer;

class OrderNotify implements Consumer
{
    // 要消费的队列名
    public $queue = 'order-notify';

    // 连接名，对应 plugin/webman/redis-queue/redis.php 里的连接`
    public $connection = 'default';

    // 消费
    public function consume($data)
    {
        if (!empty($data['body'])){
            $result = json_decode($data['body'], true);
        }
        Db::beginTransaction();
        try {
            Log::info(json_encode($data, JSON_UNESCAPED_UNICODE));
            switch ($data['cmd']){
                case 'ticket.new':
                    Order::updateOrCreate([
                        'appid' =>$data['appId'],
                        'order_no'=>$result['sn'],
                    ],[
                        'uid' => $result['uid'],
                        'appid' =>$data['appId'],
                        'order_no'=>$result['sn'],
                        'customer_id' => $result['customerUid'],
                        'order_date_time'=>date('Y-m-d'),
                        'ticket_type' => $result['ticketType'],
                    ]);
                    // 查询销售单据详情
                    $orderInfo = RequestService::ticketInfo($data['appId'],$result['sn']);
                    if (!empty($orderInfo['status']) && $orderInfo['status'] == 'success'){
                        $info = $orderInfo['data'];
                        // 判断是否网络订单
                        if (!empty($info['webOrderNo'])){
                            break;
                        }
                        if (empty($info['customerUid'])){
                            break;
                        }
                        $customerNumber = YbUser::getCustomerNumber($info['customerUid'],$data['appId']);
                        $userInfo = YbUser::where('customer_uid',$info['customerUid'])->first();
                        $goods = $info['items'];
                        $total_price = 0;
                        // 获取屏蔽商品条形码
                        $barcods = IgnoreGood::getIgnoreGoods();
                        if (!empty($goods) && !empty($barcods)){
                            foreach ($goods as $k=>$v){
                                if (in_array($v['productBarcode'],$barcods)){
                                    $goods[$k]['is_reward'] = 0;
                                    continue;
                                }
                                $goods[$k]['is_reward'] = 1;
                                $total_price += $v['sellPrice']*$v['quantity'];
                            }
                            $info['items'] = $goods;
                        }else{
                            $total_price = $info['totalAmount'];
                        }
                        $info['reward_total_price'] = $total_price;
                        $info['items'] = !empty($info['items'])?json_encode($info['items'],JSON_UNESCAPED_UNICODE):'';
                        $order = NetworkOrder::updateOrCreate([
                            'appid' =>$data['appId'],
                            'orderNo'=>$info['sn'],
                        ],[
                            'orderNo'=>$info['sn'],
                            'payMethod'=>$info['payments'][0]['code']??'',
                            'customerNumber' => $customerNumber,
                            'orderDateTime' => $info['datetime'],
                            'type' => 1,
                            'totalAmount' => $info['totalAmount'],
                            'state' => 4,
                            'orderRemark' => $info['remark'],
                            'orderSource' => $info['orderSource']??'线下收银',
                            'items' => $info['items'],
                            'contactName' => $userInfo['name']??'',
                            'contactTel' => $userInfo['phone']??'',
                            'reward_total_price' => $info['reward_total_price'],
                        ]);
                        $order = NetworkOrder::where('id', $order->id)->first();
                        $price_log = PriceLog::firstOrCreate(['appid'=>$data['appId']]);
                        if ($order->is_record == 0){
                            $proportion = Cache::get('proportion',10);
                            $price = bcmul($total_price,($proportion/100),2);
                            $price_log->increment('price', $price);
                            $price_log->save();
                            $order->is_record = 1;
                            $order->rake_price = $price;
                            if (empty($total_price)){
                                $order->is_reward = 1;
                                $order->reward_create_time = $order->orderDateTime??date('Y-m-d H:i:s');
                            }
                            $order->save();
                        }
                        $this->resultReward($data['appId']);
                    }
                    break;
                case 'ticket.reverse': // 反结账
                    if (empty($result['sn']) || empty($result['ticketType'])){
                        throw new \Exception('订单反结账失败');
                    }
                    Order::where('order_no', $result['sn'])->update(['ticket_type'=>$result['ticketType']]);
                    break;
                case 'customer.new': // 新增会员
                    YbUser::firstOrCreate([
                        'customer_uid' => $result['customerUid'],
                        'phone' => $result['phone'],
                        'name' => $result['name'],
                        'customer_number' => $result['number'],
                    ]);
                    break;
                case 'productOrder.completePay':
                    // 查询网络订单详情
                    $orderInfo = RequestService::orderInfo($data['appId'],$result['orderNo']);
                    if (!empty($orderInfo['status']) && $orderInfo['status'] == 'success'){
                        $total_price = 0;
                        $info = $orderInfo['data'];
                        Cache::set($data['appId'].'reward_order_number-'.$info['orderNo'],json_encode($info,JSON_UNESCAPED_UNICODE));
                        $goods = $info['items'];
                        // 获取屏蔽商品条形码
                        $barcods = IgnoreGood::getIgnoreGoods();
                        if (!empty($goods) && !empty($barcods)){
                            foreach ($goods as $k=>$v){
                                if (in_array($v['productBarcode'],$barcods)){
                                    $goods[$k]['is_reward'] = 0;
                                    continue;
                                }
                                $goods[$k]['is_reward'] = 1;
                                $total_price += $v['productSellPrice']*$v['productQuantity'];
                            }
                            $info['items'] = $goods;
                        }else{
                            $total_price = $info['totalAmount'];
                        }
                        $info['reward_total_price'] = $total_price;
                        $info['items'] = !empty($info['items'])?json_encode($info['items'],JSON_UNESCAPED_UNICODE):'';
                        $order = NetworkOrder::updateOrCreate([
                            'appid' =>$data['appId'],
                            'orderNo'=>$result['orderNo'],
                        ],$info);

                        $order = NetworkOrder::where('id', $order->id)->first();
                        $price_log = PriceLog::firstOrCreate(['appid'=>$data['appId']]);
                        if ($order->is_record == 0){
                            $proportion = Cache::get('proportion',10);
                            $price = bcmul($total_price,($proportion/100),2);
                            $price_log->increment('price', $price);
                            $price_log->save();
                            $order->is_record = 1;
                            $order->rake_price = $price;
                            if (empty($total_price)){
                                $order->is_reward = 1;
                                $order->reward_create_time = $order->orderDateTime??date('Y-m-d H:i:s');
                            }
                            $order->save();
                        }
                        //查询要奖励的订单
                        $reward_order = NetworkOrder::where(['is_reward'=>0,'is_record'=>1,'appid'=>$data['appId']])->whereNotNull('customerNumber')->whereNotNull('reward_total_price')->where(function ($q){
                            $q->whereNull('state')->orWhere('state','!=',3);
                        })->orderBy('id')->first();
                        $this->resultReward($data['appId']);
                    }else{
                        $info=[
                            'appid' =>$data['appId'],
                            'orderNo'=>$result['orderNo'],
                        ];
                        NetworkOrder::updateOrCreate([
                            'appid' =>$data['appId'],
                            'orderNo'=>$result['orderNo'],
                        ],$info);
                    }

                    break;
                case 'productOrder.updateProductOrder':
                case 'productOrder.createProductOrder':
                    if (!empty($result['orderNo'])){
                        NetworkOrder::updateOrCreate([
                            'appid' => $data['appId'],
                            'orderNo' => $result['orderNo'],
                        ],[
                            'appid' => $data['appId'],
                            'orderNo' => $result['orderNo'],
                            'state' => $result['state'],
                        ]);
                        // 订单取消，资金池金额扣除
                        if ($result['state'] == 3){
                            $order = NetworkOrder::where(['appid' => $data['appId'], 'orderNo' => $result['orderNo']])->first();
                            $decrease_price = RequestService::priceFormat($order->rake_price??'');
                            if (!empty($order) && !empty($decrease_price)){
                                PriceLog::where('appid',$data['appId'])->decrement('price',$decrease_price);
                            }
                        }
                    }

                    break;
            }
            Db::commit();
            RequestLog::where('message_key',$data['messageKey'])->update(['status'=>1]);
            Log::info('消费成功：---'.$data['messageKey'].'---'.$data['cmd']);
        }catch (\Throwable $e){
            Db::rollBack();
            Log::error('消费失败：---'.$data['messageKey'].'---'.$e->getMessage());
            throw new \Exception($e->getMessage());
        }

    }

    public function resultReward($appid)
    {
        //查询要奖励的订单
        $reward_order = NetworkOrder::where(['is_reward'=>0,'is_record'=>1,'appid'=>$appid])->whereNotNull('customerNumber')->whereNotNull('reward_total_price')->where(function ($q){
            $q->whereNull('state')->orWhere('state','!=',3);
        })->orderBy('id')->first();
        $reward_order->reward_total_price = RequestService::priceFormat($reward_order->reward_total_price);
        $price_log = PriceLog::where('appid',$reward_order->appid)->first();
        if ($price_log->price >= $reward_order->reward_total_price){
            $customer_id = YbUser::getCustomerId($reward_order->customerNumber,$appid);
            if (!empty($customer_id) && !empty($reward_order->reward_total_price)){
                $time =  date('Y-m-d H:i:s');
                $balance = RequestService::updateBalance($price_log->appid,$customer_id,$reward_order->reward_total_price,$time);
                if ($balance['status']=='success'){
                    $reward_order->is_reward = 1;
                    $reward_order->reward_create_time = $time;
                    $reward_order->save();
                    PriceLog::where('appid',$reward_order->appid)->decrement('price',$reward_order->reward_total_price);
                    RechargeLog::create([
                        'customer_id' => $customer_id,
                        'price' => $reward_order->reward_total_price,
                        'order_no' => $reward_order->orderNo,
                        'appid' => $reward_order->appid,
                    ]);
                }else{
                    Log::error('奖励失败：'.json_encode($balance,JSON_UNESCAPED_UNICODE).'订单号：'.$reward_order->orderNo.'会员号：'.$reward_order->customerNumber);
                }
            }else{
                $reward_order->is_reward = 1;
                $reward_order->reward_create_time = date('Y-m-d H:i:s');
                $reward_order->save();
            }
        }

    }

    // 消费失败回调
    /*
    $package = [
        'id' => 1357277951, // 消息ID
        'time' => 1709170510, // 消息时间
        'delay' => 0, // 延迟时间
        'attempts' => 2, // 消费次数
        'queue' => 'send-mail', // 队列名
        'data' => ['to' => 'tom@gmail.com', 'content' => 'hello'], // 消息内容
        'max_attempts' => 5, // 最大重试次数
        'error' => '错误信息' // 错误信息
    ]
    */
    public function onConsumeFailure(\Throwable $e, $package)
    {
        $message_key = $package['data']['messageKey']??'';
        if (!empty($message_key)){
            RequestLog::where('message_key',$message_key)->update(['status'=>0]);
        }
        Log::error('消费失败：'.$e->getMessage());
    }
}